package ui.changeweeklydetails;

import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashSet;
import java.util.Set;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import entity.general.MinTime;

public class TimePanel extends JPanel implements KeyListener {
	
	public static interface TimePanelListener
	{
		public void timePanelChanged(TimePanel tp);
	}
	
	Set <TimePanelListener> listeners = new HashSet<>();
	private JTextField hoursField;
	private JTextField minutesField;

	/**
	 * Create the panel.
	 */
	public TimePanel() {
		setPreferredSize(new Dimension(80, 32));
		setMinimumSize(new Dimension(200, 200));
		
		hoursField = new JTextField();
		hoursField.setHorizontalAlignment(SwingConstants.CENTER);
		hoursField.setText("00");
		add(hoursField);
		hoursField.setColumns(2);
		
		JLabel lblNewLabel = new JLabel(":");
		add(lblNewLabel);
		
		minutesField = new JTextField();
		minutesField.setHorizontalAlignment(SwingConstants.CENTER);
		minutesField.setText("00");
		minutesField.setColumns(2);
		add(minutesField);

		hoursField.addKeyListener(this);
		minutesField.addKeyListener(this);
	}
	
	public void setTime(MinTime time)
	{
		if(time.getHours() < 10)
			hoursField.setText("0" + time.getHours());
		else
			hoursField.setText(time.getHours() + "");
			
		if(time.getMinutes() < 10)
			minutesField.setText("0" + time.getMinutes());
		else
			minutesField.setText(time.getMinutes() + "");			
	}
	
	public MinTime getTime()
	{
		int hrs = 0;
		try
		{
			hrs = Integer.valueOf(hoursField.getText());
		}
		catch(Exception e)
		{
			
		}

		int mins = 0;
		try
		{
			mins = Integer.valueOf(minutesField.getText());
		}
		catch(Exception e)
		{
			
		}

		MinTime time = new MinTime(hrs, mins);
		return time;
	}
	
	public void addTimePanelListener(TimePanelListener tpl)
	{
		listeners.add(tpl);
	}

	@Override
	public void keyPressed(KeyEvent arg0) {
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		for(TimePanelListener tpl : listeners)
		{
			tpl.timePanelChanged(this);
		}
	}

	@Override
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void disablePanel() {
		hoursField.setText("00");
		minutesField.setText("00");
		hoursField.setEditable(false);
		hoursField.setEnabled(false);
		minutesField.setEditable(false);
		minutesField.setEnabled(false);
	}

}
